Ext.define('cloud.controller.Product', {
    extend: 'Ext.app.Controller',
    requires: ['Ext.picker.Picker'],
    config: {
        file: '',
        urldata: [],
        filedata: [],
        refs: {
            product: 'product',
            productadd: 'productadd',
            productedit: 'productedit',
            product_search: 'product #product_search',
            product_sort: 'product #product_sort',
            product_btn_add: 'product #product_btn_add',

            product_upload: 'productadd #product_upload',
            product_upload_two: 'productadd #product_upload_two',
            product_upload_three: 'productadd #product_upload_three',
            product_upload_four: 'productadd #product_upload_four',
            product_upload_five: 'productadd #product_upload_five',

            product_edit_upload: 'productedit #product_edit_upload',
            product_edit_upload_two: 'productedit #product_edit_upload_two',
            product_edit_upload_three: 'productedit #product_edit_upload_three',
            product_edit_upload_four: 'productedit #product_edit_upload_four',
            product_edit_upload_five: 'productedit #product_edit_upload_five',


            product_submit: 'productadd #product_submit',
            product_edit: 'productedit #product_edit',
            product_del: 'productedit #product_del',
            product_csid: 'productadd checkboxfield[name=product_csid]',
            product_price: 'productadd textfield[name=product_price]',
            product_edit_csid: 'productedit checkboxfield[name=product_edit_csid]',
            product_edit_price: 'productedit textfield[name=product_edit_price]',
            productSelect: 'product #productSelect',
            hidden_cpid: 'product #hidden_cpid',
            product_image_del: 'productedit dataview'



        },
        control: {
            /**
             * search product
             */
            product_search: {
                change: function () {
                    var Store = Ext.getStore('ProductAllFindStore');
                    var value = this.getProduct_search().getValue();
                    Store.clearFilter();
                    if (value != "") {
                        Store.filter('name', value, true);
                    }
                    Store.load({params: {cadid: localStorage.getItem('cadid')}});
                }
            },
            /**
             * sort product
             */
            product_sort: {
                change: function (item, newValue, oldValue) {
                    var store = Ext.getStore('ProductAllFindStore');
                    switch (newValue) {
                        case "productName_asc":
                            store.sort({
                                property: 'name',
                                direction: 'asc'
                            });
                            break;
                        case "productName_desc":
                            store.sort({
                                property: 'name',
                                direction: 'desc'
                            });
                            break;
                        case "productLasttime_asc":
                            store.sort({
                                property: 'lasttime',
                                direction: 'asc'
                            });
                            break;
                        case "lasttime_desc":
                            store.sort({
                                property: 'lasttime',
                                direction: 'desc'
                            });
                            break;
                    }
                    store.load({params: {cadid: localStorage.getItem('cadid')}});
                }
            },
            /**
             * show productadd page
             */
            product_btn_add: {
                tap: function () {
                    Ext.Viewport.mask({xtype: 'loadmask'});
                    var product = this.getProduct();
                    var productadd = this.getProductadd()||Ext.create('cloud.view.product.ProductAdd');

                    Ext.Viewport.unmask();
                    product.push(productadd);
                }
            },
            /**
             * show productList
             */
            productSelect: {
                itemtap: function (list, item, index, record) {
                    Ext.Viewport.mask({xtype: 'loadmask'});
                    var product = this.getProduct();
                    var productedit = this.getProductedit()||Ext.create('cloud.view.product.ProductEdit');
                    //分类
                    Ext.getCmp('category').setValue(record.data.category);
                    productedit.setRecord(record);
                    //规格
                    var standards = record.data.standards;
                    var picurl = record.data.picurl;
                    Ext.Ajax.request({
                        url: GLOBAL.api_url + 'standards_all_find',
                        params: {caid: localStorage.getItem('caid')},
                        scope: this,
                        success: function (response) {
                            var result = Ext.decode(response.responseText);
                            if (result.Variables.Result.code == 0) {
                                var checkboxs = [];
                                var data = result.Variables.data;

                                //图片
                                var photos = record.data.photos;
                                Ext.getCmp('product_edit_loadedImage').setSrc(picurl);
                                if (!Ext.isEmpty(photos)) {
                                    for (var i = 0; i < photos.length; i++) {
                                        i == 0 ? Ext.getCmp('product_edit_loadedImage_two').setSrc(photos[0]['url']) : '';
                                        i == 1 ? Ext.getCmp('product_edit_loadedImage_three').setSrc(photos[1]['url']) : '';
                                        i == 2 ? Ext.getCmp('product_edit_loadedImage_four').setSrc(photos[2]['url']) : '';
                                        i == 3 ? Ext.getCmp('product_edit_loadedImage_five').setSrc(photos[3]['url']) : '';
                                    }
                                }
                            }
                        }
                    });
                    Ext.Viewport.unmask();
                    product.push(productedit);
                }
            },
            /**
             * del product_image
             */
            product_del: {
                tap: function () {
                    Ext.Msg.confirm('是否删除', '', function (data) {
                        if (data == 'yes') {
                            this.getProductedit().submit({
                                url: GLOBAL.api_url + 'product_delete&cadid=' + localStorage.getItem('cadid'),
                                scope: this,
                                method: 'POST',
                                success: function (from, result) {
                                    if (result.Variables.Result.code == 0) {
                                        Ext.getStore('ProductAllFindStore').load({params: {cadid: localStorage.getItem('cadid')}});
                                        this.getProduct().pop();
                                    } else {
                                        Ext.Msg.alert(result.Variables.Message.messagestr);
                                    }
                                }
                            });
                        }
                    }, this);
                }
            },
            /**
             * upload
             */
            product_upload: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_loadedImage';
                    file['display'] = 1;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_upload_two: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_loadedImage_two';
                    file['display'] = 2;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_upload_three: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_loadedImage_three';
                    file['display'] = 3;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_upload_four: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_loadedImage_four';
                    file['display'] = 4;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_upload_five: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_loadedImage_five';
                    file['display'] = 5;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_edit_upload: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_edit_loadedImage';
                    file['display'] = 1;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_edit_upload_two: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_edit_loadedImage_two';
                    file['display'] = 2;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_edit_upload_three: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_edit_loadedImage_three';
                    file['display'] = 3;

                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_edit_upload_four: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_edit_loadedImage_four';
                    file['display'] = 4;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },
            product_edit_upload_five: {
                loadsuccess: function (dataurl, m, e, file) {
                    var img_name = 'product_edit_loadedImage_five';
                    file['display'] = 5;
                    this.upload(dataurl, m, e, file, img_name);
                }
            },

            /**
             * submit product
             */
            product_submit: {
                tap: function () {
                    if (Ext.isEmpty(Ext.getCmp('product_name').getValue()))
                        return Ext.Msg.alert('请输入景点名称');
                    if (Ext.isEmpty(Ext.getCmp('explain').getValue()))
                        return Ext.Msg.alert('请输入景点介绍');
                    Ext.Viewport.mask({xtype: 'loadmask'});
                    //规格ID
                    var csid = [12,291,22];
                        arr_csid = document.getElementsByName('product_csid'),
                        arr_price = document.getElementsByName('product_price');
                    var price = [];
                    for (var i = 0; i < arr_csid.length; i++) {
                        if (arr_csid[i].checked) {
                            price.push(arr_price[i].value == '' ? -1 : arr_price[i].value)
                        }
                    }
                    var price_array = price.join(',');
                    var csid_array = csid.join(',');
                    this.getProductadd().submit({
                        url: GLOBAL.api_url + 'product_add&cadid=' + localStorage.getItem('cadid'),
                        scope: this,
                        method: 'POST',
                        params: {
                            //传递参数
                            csid_array: csid_array,
                            price_array: price_array
                        },
                        success: this.executeSuccess
                    });
                    Ext.Viewport.unmask();
                }
            },
            /**
             * edit product
             */
            product_edit: {
                tap: function () {
                    if (Ext.isEmpty(Ext.getCmp('product_name').getValue()))
                        return Ext.Msg.alert('请输入景点名称');
                    if (Ext.isEmpty(Ext.getCmp('explain').getValue()))
                        return Ext.Msg.alert('请输入景点介绍');

                    Ext.Viewport.mask({xtype: 'loadmask'});
                    var csid = [22,33,55],
                        arr_csid = document.getElementsByName('product_edit_csid'),
                        arr_price = document.getElementsByName('product_edit_price');
                    var price = [];
                    for (var i = 0; i < arr_csid.length; i++) {
                        if (arr_csid[i].checked) {
                            price.push(arr_price[i].value == '' ? -1 : arr_price[i].value)
                        }
                    }
                    var price_array = price.join(',');
                    var csid_array = csid.join(',');
                    this.getProductedit().submit({
                        url: GLOBAL.api_url + 'product_update&cadid=' + localStorage.getItem('cadid'),
                        scope: this,
                        method: 'POST',
                        params: {
                            csid_array: csid_array,
                            price_array: price_array
                        },
                        success: this.executeSuccess
                    });
                    Ext.Viewport.unmask();
                }
            }
        }
    },
    upload: function (dataurl, m, e, file, img_name, display) {
        var me = this;
        this.setFile(file);
        var display = display;
        image = [];
        // 储存file
        files = this.getFiledata();
        files.push(file);
        this.setFiledata(files);
        console.log(files);
        var image = Ext.getCmp(img_name);
        image.setSrc(dataurl);
    },
    executeSuccess: function (from, result) {
        if (result.Variables.Result.code == 0) {
            /**
             *  start upload
             */
            Ext.Viewport.mask({xtype: 'loadmask'});
            var filedata = this.getFiledata();
            var filelen = filedata.length
            if (filelen > 0) {
                var looplen = 1;
                var subthis = this;
                Ext.each(filedata, function (file) {
                    var http = new XMLHttpRequest();
                    var form = new FormData();
                    form.append('Filedata', file);
                    var url = GLOBAL.api_url + 'product_attachment_upload&cpid=' + result.Variables.data.id + '&display=' + file['display'];
                    if (http.upload && http.upload.addEventListener) {
                        // Response handler
                        http.onreadystatechange = function (e) {
                            if (this.readyState == 4) {
                                if (this.status == 200) {
                                    var returnText = Ext.decode(this.responseText);
                                    if (returnText.Variables.Result.code == 0) {
                                        var attachid = returnText.Variables.data.attachid;
                                        if (looplen >= filelen) {
                                            Ext.Viewport.unmask();
                                            Ext.getStore('ProductAllFindStore').load({params: {cadid: localStorage.getItem('cadid')}});
                                            subthis.getProduct().pop();
                                        } else {
                                            looplen = looplen + 1;
                                        }
                                    }
                                }
                            }
                        };
                        // Error handler
                        http.upload.onerror = this.actionfailure;
                    }
                    http.open('POST', url);
                    http.send(form);

                });
                this.setFiledata([]);
            } else {
                Ext.Viewport.unmask();
                Ext.getStore('ProductAllFindStore').load({params: {cadid: localStorage.getItem('cadid')}});
                this.getProduct().pop();
            }
            /**
             * end upload
             */
        } else {
            Ext.Msg.alert(result.Variables.Message.messagestr);
        }
    },
    actionfailure: function () {//请求失败时执行操作
        Ext.Viewport.unmask();
        Ext.Msg.alert('请求失败', '服务器维护中....');
    },

    checkboxs:function( standards, data, checkFlag){
        var checkboxs;
        checkboxs={
                layout: 'hbox',
                items: [
                {
                    style: '-webkit-box-orient: horizontal;',
                    xtype: 'checkboxfield',
                    name: 'product_edit_csid',
                    label: data.explain,
                    value: data.csid,
                    labelWidth: '80%',
                    width: '70%',
                    checked: checkFlag
                },
                {xtype: 'textfield', width: '30%', style: '-webkit-box-orient: horizontal;', name: 'product_edit_price', label: '价格', value: standards, placeHolder: '1￥'}
            ]
        };
        return(checkboxs)
    }


});